package com.fiap.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.fiap.model.User;

public class DatabaseHelper extends SQLiteOpenHelper {

	private static final String TAG = "DatabaseHelper";
	
	private static final String DATABASE_NAME = "Runners";
	private static int VERSION = 1;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE users (" +
				"_id INTEGER PRIMARY KEY, " +
				"username TEXT, " +
				"email TEXT," +
				"weight REAL," +
				"height REAL);");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}
	
	public void addUser(long id, String username, String email) {
        SQLiteDatabase db = this.getWritableDatabase();
 
        ContentValues values = new ContentValues();
        values.put("_id", id);
        values.put("username", username);
        values.put("email", email);
 
        db.insert("users", null, values);
        db.close();
    }
	
	public void updateUserInitialInfo(String weight, String height, Long id) {

		SQLiteDatabase db = this.getWritableDatabase();
        String strFilter = "_id=" + id;
        
        ContentValues values = new ContentValues();
        values.put("weight", weight);
        values.put("height", height);
 
        db.update("users", values, strFilter, null);
        db.close();
    }
	
	public int getRowCount() {
        String countQuery = "SELECT  * FROM users";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        int rowCount = cursor.getCount();
        db.close();
        cursor.close();
         
        return rowCount;
    }
	
	 /**
     * Re crate database
     * Delete all tables and create them again
     * */
    public void resetTables(){
        SQLiteDatabase db = this.getWritableDatabase();
        // Delete All Rows
        db.delete("users", null, null);
        db.close();
    }
    
    public User getUser(){ 
    	Log.w(TAG, "getUserEmail start.");
    	SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("select _id, username, email from users", null);
        if(cursor != null) {
        	cursor.moveToFirst();
        }
        
        Long id = cursor.getLong(0);
        String username = cursor.getString(1);
        String email = cursor.getString(2);
        
        
        User user = new User(id, username, email);
        db.close();
        
        Log.w(TAG, "getUserEmail end. return: " + user);
		return user;
    }

}
